import { reactive, computed, toRefs } from "vue";

// websocket hook
/**
 *  连接 断开连接 发送消息
 *  断线重连 
 *  心跳检测
 */
export function useWebSocket(url: string) {
    const SocketStatus = {
        Connecting: '正在连接...', //表示正在连接，这是初始状态。
        Connected: '连接已建立', //表示连接已经建立。
        Disconnecting: '连接正在关闭', //表示连接正在关闭。
        Disconnected: '连接已断开' //表示连接已经关闭
    }
    
    const DEFAULT_OPTIONS = {
        url: '', // websocket url
        heartBeatData: '', // 你的心跳数据
        heartBeatInterval: 60 * 1000, // 心跳间隔，单位ms
        reconnectInterval: 5 * 1000, // 断线重连间隔，单位ms
        maxReconnectAttempts: 10 // 最大重连次数
    }

    const state = reactive({
        socket: null as WebSocket | null,
        message: "",
        messages: [] as string[],
    });

    const sendMessage = () => {
        if (state.socket) {
            state.socket.send(state.message);
            state.messages.push(state.message);
            state.message = "";
        }
    };
    const connect = () => {
        state.socket = new WebSocket(url);
        state.socket.onmessage = (event) => {
            state.messages.push(event.data);
        };
    }
    const disconnect = () => {
        if (state.socket) {
            state.socket.close();
            state.socket = null;
        }
    }

    return {
        ...toRefs(state),
        sendMessage,
        connect,
        disconnect
    }
}